/**
 *
 * @author zzhijie
 * @date 2021-04-23
 */
import mixin from "../mixins/mixin";
import {getEvents} from '../utils';

export default {
  name: "f-page",
  mixins: [mixin],
  props: {
    config: {
      type: Object,
    },
    page: {
      type: Object,
      default: () => ({})
    },
    hasPageChangeHandler: {
      type: Boolean
    }
  },
  data() {
    return {
      globalConfig: this.$crudConfig || {},  // 全局注入的配置
    };
  },
  computed: {
    /**
     * 分页默认字段
     * @returns {{current: string, total: string, size: string, sizes: string}}
     */
    pageProp() {
      let {
        current = "currentPage",
        size = "pageSize",
        total = "total",
        sizes = "sizes"
      } = this.config.pageProp || this.globalConfig.pageProp || {};
      return {current, size, total, sizes};
    },
  },
  methods: {
    /**
     * 点击分页
     * @param pageSize
     */
    handleSizeChange(pageSize) {
      this.page[this.pageProp.size] = pageSize;
      this.handlePageChange();
    },
    /**
     * 切换每页显示条数
     * @param curPage
     */
    handleCurrentChange(curPage) {
      this.page[this.pageProp.current] = curPage;
      this.handlePageChange();
    },
    /**
     * 处理分页事件
     */
    handlePageChange() {
      if (this.hasPageChangeHandler) {
        this.$emit("pageChange", this.page);
      } else {
        this.$emit("submitSearch", this.$parent.params);
      }
    },
  },
  render() {
    let {current, size, total, sizes} = this.pageProp;
    let {$page = {}} = this.config;
    let data = {...getEvents($page.on), ...$page.props, ...$page.attrs};
    return (
      <el-pagination
        {...data}
        onSizeChange={this.handleSizeChange}
        onCurrentChange={this.handleCurrentChange}
        current-page={+this.page[current] || 1}
        page-sizes={this.page[sizes]}
        page-size={+this.page[size] || 10}
        total={+this.page[total] || 0}
        layout="total, sizes, prev, pager, next, jumper"/>
    );
  }
};
